<?php
namespace app\index\controller;

use think\Controller;
use think\Exception;
use think\Request;

class Order extends Base
{
    public function index(Request $request)
    {
        $user = $this->getLoginUser();
        if (!$user)
        {
            $this->error('请登录', 'user/login');
        }
        $id = $request->param('id', 0,'intval');
        if (!$id)
        {
            $this->error('参数不合法');
        }
        $count = $request->param('deal_count', 0,'intval');
        $totalPrice = $request->param('total_price', 0,'floatval');
        $test = round($totalPrice, 2);
        $deal = model('Deal')->find($id);
        if (!$deal || $deal['status'] != 1)
        {
            $this->error('商品不存在');
        }
        if (empty($_SERVER['HTTP_REFERER']))
        {
            $this->error('请求不合法');
        }
        $orderSn = setOrderSn();
        // 组装入库数据
        $data = [
            'out_trade_no' => $orderSn,
            'user_id' => $user['id'],
            'username' => $user['username'],
            'deal_id' => $id,
            'deal_count' => $count,
            'total_price' => $test,
            'referer' => $_SERVER['HTTP_REFERER'],
        ];
        try
        {
            $orderid = model('Order')->add($data);
        } catch (Exception $e)
        {
            $this->error('订单处理失败');
        }

        $this->redirect('pay/index', ['id' => $orderid]);
    }

    public function confirm(Request $request)
    {
        if (!$this->getLoginUser())
        {
            $this->error('请登录', 'user/login');
        }
        $id = $request->param('id', 0,'intval');
        if (!$id)
        {
            $this->error('参数不合法');
        }
        $count = $request->param('count', 1,'intval');
        $deal = model('Deal')->find($id);
        if (!$deal || $deal['status'] != 1)
        {
            $this->error('商品不存在');
        }

        $this->assign([
            'controller' => 'pay',
            'count' => $count,
            'deal' => $deal
        ]);
        return $this->fetch();
    }

}
